package io.netty.example.demo;

import io.netty.channel.*;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class DemoSocketServerHandler
        extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        System.out.println("Client Address ====== " + ctx.channel().remoteAddress());
        //创建一个观察者
        ChannelPromise channelPromise = ctx.newPromise();
        channelPromise.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                System.out.println("观察者模式-监听事件");
            }
        });
                                                                            //添加-监听通知
        ctx.channel().writeAndFlush("from server:" + UUID.randomUUID(),channelPromise);
        TimeUnit.MILLISECONDS.sleep(500);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
                                Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
